package com.mzp.XbShop.controller;

import com.alibaba.fastjson.JSONObject;
import com.mzp.XbShop.common.entity.Result;
import com.mzp.XbShop.pojo.User;
import com.mzp.XbShop.service.UserService;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;
import java.util.UUID;

@Controller
@RequestMapping("/wx_login")
public class wxController {

    @Autowired
    private UserService userService;
    @RequestMapping
    public String wxlogin(HttpServletRequest request,HttpServletResponse response) throws Exception {

        Properties prop = new Properties();
        prop.load(wxController.class.getClassLoader().getResourceAsStream("config.properties"));

        String appId = prop.getProperty("wx.AppID");
        String appSecret = prop.getProperty("wx.AppSecret");


        String code = request.getParameter("code");

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + appId +
                "&secret=" + appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";

        // 根据code请求access_toekn
        HashMap<String, String> auth = execute(url);

        String access_token = auth.get("access_token");

        url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + auth.get("openid}");

        HashMap<String, Object> userInfo = execute(url);

        // 根据openid查询用户
        User user = userService.findByWxOpenId(auth.get("openid"));

        if (user == null) {

            // 代表第一次使用微信扫码登录
            user = new User();


            // 性别
            user.setSex(Integer.valueOf(userInfo.get("sex").toString()));

            // 用户的昵称
            user.setUsername(userInfo.get("nickname").toString());

            // 随机用户名(11位随机字符串)
            user.setUsername(UUID.randomUUID().toString().substring(36 - 15));

            // 设置微信的openid
            user.setWechat(userInfo.get("openid").toString());

            // 注册一个新的用户
           userService.insert(user);

            // 重新查询新的用户
            user = userService.findByWxOpenId(auth.get("openid"));
        }
//
//        // 更改用户登录时间
//        userService.updateLoginTime(user.getId());

        request.getSession().setAttribute("userInfo", user);
        return "/view/home";
    }

    // 执行http请求
    public HashMap execute(String url) {

        try {
            // 创建HttpClient实例
            CloseableHttpClient client = HttpClients.createDefault();

            HttpGet httpGet = new HttpGet(url);

            CloseableHttpResponse response = client.execute(httpGet);

            org.apache.http.HttpEntity entity1 = response.getEntity();

            String jsonStr = EntityUtils.toString(entity1, "UTF-8");

            return JSONObject.parseObject(jsonStr, HashMap.class);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
